<template>
  <div class="mydiscount">
    <div class="header" @click="changeShow(false)">
      <div class="discountKinds">
        <span :class="activeKind ? 'activeKind' : ''" @click="changeActiveKinds(true)">优惠券</span>
        <span :class="activeKind ? '' : 'activeKind'" @click="changeActiveKinds(false)">福利券</span>
      </div>
      <div ref="container"></div>
      <div class="inputBox">
        <div class="address" style="width:72px">
          <div @click.stop="pickerShow" class="overd">{{address}}</div>
          <!-- <div v-for="(item,index) in citys" :key='index'> -->
          <!-- <div style="width:100px;height:200px;position:fixed;top:0;left:0">clay-{{citys}}</div>
          <div style="width:100px;height:200px;position:fixed;top:60px;left:0">err-{{err}}</div>-->
          <!-- </div> -->
          <div class="addressIcon">
            <img src="../../assets/images/xiajiantou.png" width="100%" />
          </div>
        </div>
        <div class="innerInputBox">
          <div class="searchIcon">
            <img
              src="../../assets/images/chaxun.png"
              style="width:20px;height:20px;  line-height:70px"
            />
          </div>
          <input type="text" placeholder="搜索券名称" v-model="search" />
        </div>
        <div class="right_filter" @click.stop="changeShow('filterButton')">
          <div class="filterIcon">
            <img src="../../assets/images/filter-fill.png" width="100%" />
          </div>
          <div class="right_title">筛选</div>
        </div>
      </div>
    </div>
    <div class="contant">
      <van-tabs v-model="active" sticky swipeable animated lazy-render @change="chooseKind">
        <van-tab :title="'已领取('+Number(list2.length+useDateTimeList.length)+')'">
          <DiscountList openDescriptTitle="云车服务中心" useStatues="have" :list="list2" />
          <div class="notReachTime" v-if="useDateTimeList.length > 0">
            <div class="notReachTimeTitle">未到使用时间</div>
            <DiscountList
              openDescriptTitle="云车服务中心"
              :notReactTime="true"
              useStatues="have"
              :list="useDateTimeList"
            />
          </div>
        </van-tab>
        <van-tab :title="'已使用('+usedList.length+')'">
          <DiscountList openDescriptTitle="云车服务中心" useStatues="used" :list="usedList" />
        </van-tab>
        <van-tab :title="'已过期('+overTimeList.length+')'">
          <DiscountList openDescriptTitle="云车服务中心" useStatues="overtime" :list="overTimeList" />
        </van-tab>
      </van-tabs>
      <!-- 过滤弹窗 -->
      <van-popup v-model="show" position="right" lazy-render>
        <div class="filterBox">
          <div class="differentKind">
            <div class="title">会员卡名称</div>
            <div class="typeList">
              <div
                class="myRect"
                v-for="(item, index) in vipNameList"
                :key="index"
                @click="item.Selected = !item.Selected"
                :class="item.Selected ? 'selectedStyle' : ''"
              >{{ item.name }}</div>
            </div>
          </div>
          <div class="differentKind">
            <div class="title">优惠券类型</div>
            <div class="typeList">
              <div
                class="myRect"
                v-for="(item, index) in discountTypeList"
                :key="index"
                @click="item.Selected = !item.Selected"
                :class="item.Selected ? 'selectedStyle' : ''"
              >{{ item.name }}</div>
            </div>
          </div>
          <div class="differentKind">
            <div class="title">有效期</div>
            <div class="typeListTime">
              <div
                class="chooseTime"
                @click="chooseTime('start')"
              >{{ time.timeStart ? time.timeStart : "开始时间" }}</div>
              <div class="tiemMiddle">-</div>
              <div
                class="chooseTime"
                @click="chooseTime('end')"
              >{{ time.timeEnd ? time.timeEnd : "结束时间" }}</div>
            </div>
          </div>
          <div class="differentKind">
            <div class="title">门店类型</div>
            <div class="typeList">
              <div
                class="myRect"
                v-for="(item, index) in storeTypeList"
                :key="index"
                @click="item.Selected = !item.Selected"
                :class="item.Selected ? 'selectedStyle' : ''"
              >{{ item.name }}</div>
            </div>
          </div>
          <div class="twoButton">
            <button @click="reset">重置</button>
            <button @click="ensure">确定</button>
          </div>
        </div>
      </van-popup>
      <!-- 时间选择器弹窗 -->
      <van-popup v-model="time.timePicker" position="bottom" :style="{ width: '100%' }">
        <van-datetime-picker
          v-model="time.currentDate"
          type="date"
          :min-date="time.minDate"
          :max-date="time.maxDate"
          @confirm="timePickerenSure"
          @cancel="time.timePicker = false"
        />
      </van-popup>
      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          show-toolbar
          :columns="columns"
          @cancel="showPicker = false"
          @confirm="onConfirm"
          value-key='name'
          ref='myPicker'
        />
      </van-popup>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Dialog } from "vant";
Vue.use(Dialog);
import DiscountList from "../../components/myDis";
import wx from "weixin-js-sdk";
import { Picker } from "vant";

Vue.use(Picker);
// const citys = {
//   浙江: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
//   福建: ['福州', '厦门', '莆田', '三明', '泉州'],
// };
// import QQMapWX from './qqmap-wx-jssdk.js'
// import
// var  QQMapWX = require( "./qqmap-wx-jssdk.js")
// var  QQMapWX = require( "qqmap-wx-jssdk")
// var qqmapsdk = new QQMapWX({
// 	  key: 'PARBZ-4SW3K-XVEJ7-AUUZL-6CEMH-PPFF7'
// 	})
// var map = new qq.maps.Map
function removeEmptyChild(list) {
  const res = [];
  // for (const item of list) {
  // 	const { child, ...other } = item;
  // 	if (child.length) {
  // 		const val = other;
  // 		val.child = removeEmptyChild(child);
  // 		res.push(val);
  // 	} else {
  // 		res.push(other);
  // 	}
  // }
  // return res;
}
export default {
  components: {
    DiscountList
  },
  computed: {
    list2() {
      return this.list.filter(item => {
        return item.status == 1;
      });
    },
    usedList() {
      return this.list.filter(item => {
        return item.status == 2;
      });
    },
    overTimeList() {
      return this.list.filter(item => {
        return item.status == 3;
      });
    }
  },
  data() {
    return {
      endarr: "",
      provinceCode: "", //省编码
      cityCode: "", //市编码
      districtCode: "", //区编码
      address: "地理位置",
      showPicker: false,
      columns: [],
      err: "",
      // citys:'',
      arr2: "", //优惠券类型
      arr: "", //会员id
      search: "", //搜索关键字
      activeKind: true, //true控制优惠券 false控制福利券
      active: "", //控制tabs,
      show: false, //控制筛选模态框
      //会员卡名称功能列表
      vipNameList: [],
      discountTypeList: [], //优惠券类型列表
      storeTypeList: [], //门店类型列表
      list: [], //已领取并可以使用优惠券列表
      useDateTimeList: "", //已领取未到时间
      time: {
        minDate: new Date(2020, 0, 1), //时间选择器最小日期
        maxDate: new Date(2025, 10, 1), //时间选择器最大日期
        currentDate: new Date(),
        timePicker: false, //时间选择器弹窗层控制
        timeStart: "", //选择的开始时间
        timeEnd: "", //选择的结束时间
        timeType: "" //当前弹窗是开始时间或结束时间的类型
      }
    };
  },
  mounted() {
    // this.getLocation();
  },
  created() {
    let customerCode = localStorage.getItem("customerCode") || "";
    if (customerCode == "") {
      localStorage.setItem("customerCode", this.$route.query.customerCode);
    }
    if (
      customerCode != this.$route.query.customerCode &&
      this.$route.query.customerCode != undefined
    ) {
      localStorage.setItem("customerCode", this.$route.query.customerCode);
    }
    this.getList();
    this.getVipList();
    this.getRegion();
  },
  methods: {
    getRegion() {
      let params = {
        sysCustomerCode: localStorage.getItem("customerCode")
      };
      this.$api.getRegion(params).then(res => {
        res.data.map(val => {
          // val.text = val.name || "";
          val.children = val.child || [];
          if (val.children == "") {
            val.children = [{ name: "", children: [{ name: "", child: [] }] }];
          } else {
            val.children.map(item => {
              // item.text = item.name || "";
              item.children = item.child || [];
              // if(item.children=='')return ''
              if (item.children == "") {
                item.children = [
                  { name: "", children: [{ name: "", child: [] }] }
                ];
              } else {
                item.children.map(ends => {
                  // ends.text = ends.name || "";
                });
              }
            });
          }
        });
        this.columns = res.data;
      });
    },
    onConfirm(val,idx) {
      this.address=val[2]||val[1]||val[0]
      // console.log(val,idx,this.address)
      // console.log(this.$refs.myPicker.getColumnValue(0,1,2))
      // console.log(this.$refs.myPicker.getColumnValues(0,1,2))
      // console.log(this.$refs.myPicker)
      this.provinceCode= this.columns[idx[0]].code||'' //省编码
      this.cityCode=this.columns[idx[0]].children[idx[1]].code||'', //市编码
      this.districtCode=this.columns[idx[0]].children[idx[1]].children[idx[2]].code||"", //区编码
      this.showPicker = false;
      this.getList()
    },
    pickerShow() {
      this.showPicker = true;
    },
    searchKey() {
      var latitude = 11.11;
      var longitude = 11.11;
      this.$http.get({
        url:
          "http://api.map.baidu.com/geocoder/v2/?ak=A8cc7c770c518c3fc4714a4ca452aadc&callback=renderReverse&location=" +
          latitude +
          "," +
          longitude +
          "&output=json&pois=0",
        cache: true,
        dataType: "jsonp",
        success: function(result) {
          console.log(result);
        }
      });
    },
    getLocation() {
      let params = {
        appId: "wx91e0103162eedd4c",
        url: location.href.split("#")[0]
      };
      this.$api.getSDK(params).then(res => {
        if (res.code == "10000") {
          var sig = res.data.signature;
          wx.config({
            debug: true,
            appId: res.data.appId, // 必填,公众号的唯一标识
            timestamp: res.data.timestamp, // 必填,生成签名的时间戳
            nonceStr: res.data.noncestr, // 必填,生成签名的随机串
            signature: res.data.signature, // 必填,签名
            jsApiList: ["getLocation"] // 必填,需要使用的JS接口列表
          });
          let that = this;
          wx.ready(() => {
            wx.getLocation({
              type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
              success: function(res2) {
                console.log(res2);

                // var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                // var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                // var accuracy = res.accuracy; // 位置精度
              },
              cancel: function(res) {
                alert("用户拒绝授权获取地理位置");
              }
            });
          });
        } else {
          alert(res.message);
        }
      });
    },
    locationChange() {
      console.log(111);
      wx.ready(() => {
        wx.getLocation({
          type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
          success: function(res) {
            console.log("地理位置", res);
            // alert(JSON.stringify(res));
            var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
            // $("#latitude").val(latitude);
            var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
            // $("#longitude").val(longitude);
            var speed = res.speed; // 速度，以米/每秒计
            // $("#speed").val(speed);
            var accuracy = res.accuracy; // 位置精度
            // $("#accuracy").val(accuracy);
          },
          cancel: function(res) {
            alert("用户拒绝授权获取地理位置");
          }
        });
      });
    },
    getVipList() {
      let params = {
        sysCustomerCode: localStorage.getItem("customerCode")
      };
      this.$api.getVipList(params).then(res => {
        console.log(res.data);
        res.data.vipCardList.map(val => {
          val.Selected = false;
        });
        res.data.couponTypeList.map(val => {
          val.Selected = false;
        });
        res.data.jsonArrayMerchantType.map(val => {
          val.Selected = false;
        });
        this.storeTypeList = res.data.jsonArrayMerchantType;
        this.discountTypeList = res.data.couponTypeList;
        this.vipNameList = res.data.vipCardList;
      });
    },
    chooseKind() {
      console.log(`触发tabs类型切换${this.active}`, Number(this.active + 1));
    },
    getList() {
      let params = {
        sysCustomerCode: localStorage.getItem("customerCode"),
        status: Number(this.active + 1),
        condition: this.search, //搜索信息
        typeId: this.arr2, //优惠券类型 0-全部 1-满减 2-立减 3-折扣
        vipCardId: this.arr, //会员id
        merchantType: this.endarr, //门店类型
        startTime: this.time.timeStart, //开始时间
        endTime: this.time.timeEnd, //结束时间
        provinceCode: this.provinceCode, //省编码
        cityCode: this.cityCode, //市编码
        districtCode: this.districtCode //区编码
      };
      this.$api.myList(params).then(res => {
        res.data.customersList.map(val => {
          if (!!val.availableDeal) {
            val.availableDeal = val.availableDeal.split(",");
          }
        });
        res.data.useDateTimeList.map(val => {
          if (!!val.availableDeal) {
            val.availableDeal = val.availableDeal.split(",");
          }
        });
        this.list = res.data.customersList || [];
        this.useDateTimeList = res.data.useDateTimeList || [];
      });
    },
    //顶部优惠券类型切换
    changeActiveKinds(boolean) {
      this.activeKind = boolean;
    },
    //开关遮罩层
    changeShow(boolean) {
      console.log("操作遮罩层");
      //如果点击的是筛选按钮，就进行开关门样式
      if (boolean == "filterButton") {
        this.show = !this.show;
      } else {
        this.show = boolean;
      }
    },
    //点击选择时间
    chooseTime(type) {
      this.time.timePicker = true;
      this.time.timeType = type;
    },
    //时间选择器确认按钮
    timePickerenSure(value) {
      value = this.timeFilter(value);
      let { timeType } = this.time;
      if (timeType == "start") {
        this.time.timeStart = value;
      } else {
        this.time.timeEnd = value;
      }
      this.time.timePicker = false;
    },
    //new data()过滤成“年-月-日”格式
    timeFilter(value) {
      let date = new Date(value);
      console.log(date);
      let connector = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      let currentdate = year + connector + month + connector + strDate;
      return currentdate;
    },
    //点击筛选中的确定按钮
    ensure() {
      let arr = [],
        arr2 = [],
        arr3 = [],
        arr4 = [],
        arr5 = [],
        arr6 = [];
      arr = this.vipNameList.filter(val => {
        return val.Selected == true;
      });
      arr2 = this.discountTypeList.filter(val => {
        return val.Selected == true;
      });
      arr5 = this.storeTypeList.filter(val => {
        return val.Selected == true;
      });
      arr5.map(val => {
        arr6.push(val.code);
      });
      arr.map(val => {
        arr3.push(val.id);
      });
      arr2.map(val => {
        arr4.push(val.id);
      });
      if (arr3.indexOf(0) > -1) {
        arr3 = 0;
      } else {
        arr3 = arr3.join(",");
      }
      if (arr4.indexOf(0) > -1) {
        arr4 = 0;
      } else {
        arr4 = arr4.join(",");
      }
      if (arr6.indexOf("ALL") > -1) {
        arr6 = 0;
      } else {
        arr6 = arr6.join(",");
      }
      this.arr = arr3;
      this.arr2 = arr4;
      this.beginTime = this.time.timeStart || "";
      this.endTime = this.time.timeEnd || "";
      this.endarr = arr6;
      this.changeShow(false);
      this.getList();
    },
    //点击筛选中的重置按钮
    reset() {
      console.log("执行筛选重置操作");
      this.time.timeStart = null;
      this.time.timeEnd = null;
      this.vipNameList.forEach(item => {
        item.Selected = false;
      });
      this.discountTypeList.forEach(item => {
        item.Selected = false;
      });
      this.storeTypeList.forEach(item => {
        item.Selected = false;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.selectedStyle {
  background: #ffebed !important;
}
.mydiscount {
  // background: #f1f1f1 !important;
  .header {
    background: #ef3b4f;
    height: 200px;
    .discountKinds {
      // padding-top: 126px;
      padding: 20px 0;
      display: flex;
      justify-content: center;
      span {
        display: inline-block;
        width: 200px;
        height: 60px;
        color: #ffffff;
        background: #ef3b4f;
        text-align: center;
        font-size: 24px;
        line-height: 60px;
        border-radius: 30px;
      }
      .activeKind {
        color: #ef3b4f;
        background: #ffffff;
      }
    }
    .inputBox {
      padding: 0 26px 30px 30px;
      height: 70px;
      display: flex;
      align-items: center;
      font-size: 28px;
      justify-content: space-between;
      > div {
        height: 70px;
        line-height: 70px;
        color: #ffffff;
      }
      .addressIcon {
        width: 22px;
        height: 17px;
        // padding: 0 0 0 14px;
        display: inline-block;
        img {
          vertical-align: middle;
        }
      }
      .filterIcon {
        width: 42px;
        height: 30px;
        // padding: 0 14px 0 0;
        // display: inline-block;
        img {
          padding-top: 18px;
          // align-items: center;
          // vertical-align: middle;
        }
      }
      .innerInputBox {
        height: 70px;
        width: 420px;
        border-radius: 35px;
        line-height: 70px;
        background: #ffffff;
        display: flex;
        align-content: center;
        align-items: center;
        .searchIcon {
          height: 28px;
          height: 28px;
          padding: 0 20px;
          display: inline-block;
        }
        input {
          height: 100%;
          border: 0;
          margin: 0;
          padding: 0;
          border-radius: 35px;
          font-size: 28px;
          color: #272727;
        }
      }
    }
  }
  .contant {
    position: relative;
    /deep/ .van-list {
      padding-top: 20px;
      background-color: #f1f1f1;
    }
    /deep/ .van-tab__text {
      font-size: 28px;
      color: #272727;
    }
    /deep/ .van-tab.van-tab--active.van-ellipsis .van-tab__text {
      color: #ef3b4f;
    }
    /deep/ .van-tabs__wrap.van-hairline--top-bottom {
      height: 116px !important;
      border-bottom: 1px solid #cdcdcd;
    }
    /deep/ .van-tab.van-ellipsis {
      line-height: 116px;
    }
    /deep/ .van-tabs__line {
      width: 160px !important;
      height: 6px;
      background-color: #ef3b4f;
    }
    /deep/ [class*="van-hairline"]::after {
      border: 0;
    }
    /deep/ .van-popup.van-popup--right {
      height: calc(100% - 200px);
      width: 580px;
      // top: 740px;
      top: 200px;
      position: fixed;
      overflow-y: scroll;
      transform: translate3d(0, 0, 0);
      transition: transform 0s;
      background: rgba(0, 0, 0, 0);
    }
    /deep/ .van-overlay {
      position: fixed;
      top: 200px;
      left: 0;
      z-index: 1;
      width: 100%;
      height: 90%;
      background-color: rgba(0, 0, 0, 0.7);
    }
    .filterBox {
      min-height: 100%;
      display: flex;
      flex-direction: column;
      .differentKind {
        padding: 0 33px;
        background: #ffffff;

        .title {
          font-size: 34px;
          color: #272727;
          padding: 30px 0;
        }
        .typeList {
          display: flex;
          flex-wrap: wrap;
          width: 100%;

          // grid-template-columns: repeat(3, auto);
          // grid-row-gap: 20px;
          // grid-column-gap: 20px;
          .myRect {
            margin-bottom: 20px;
            margin-right: 20px;
            height: 80px;
            width: 150px;
            line-height: 80px;
            text-align: center;
            font-size: 28px;
            color: #272727;
            border-radius: 10px;
            background-color: #f5f5f9;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        .typeListTime {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .chooseTime {
            box-sizing: border-box;
            height: 80px;
            width: 240px;
            border-radius: 10px;
            background: #ffffff;
            border: 1px solid #cdcdcc;
            line-height: 80px;
            text-align: center;
            font-size: 28px;
            color: #272727;
          }
          .tiemMiddle {
            font-size: 40px;
            color: #cdcdcc;
          }
        }
      }
      .twoButton {
        flex: 1;
        display: flex;
        align-items: flex-end;
        box-sizing: border-box;
        padding-top: 60px;
        background: #ffffff;
        button {
          border: 0;
          border-top: 1px solid #cdcdcd;
          box-sizing: border-box;
          background: #ffffff;
          height: 100px;
          width: 50%;
          color: #272727;
          font-size: 28px;
          padding: 0;
          &:last-of-type {
            color: #4883c0;
            border-left: 1px solid #cdcdcd;
          }
        }
      }
    }
    .notReachTime {
      .notReachTimeTitle {
        font-size: 24px;
        color: #737373;
        background: #fff;
        padding: 28px 0 8px 50px;
      }
    }
  }
}
.address {
  display: flex;
  justify-content: left;
}
.right_filter {
  display: flex;
}
.right_title {
  width: 100%;
}
.overd{
  
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>
